'use strict';

const { IoTClient, PubBroadcastRequest, QueryDeviceRequest } = require('@alicloud/iot20180120');
const { Config } = require('@alicloud/openapi-client');
const { RuntimeOptions } = require('@alicloud/tea-util');
const { Client } = require('@alicloud/sts20150401');
const { Config as StsConfig } = require('@alicloud/openapi-client');

// 获取临时凭证
async function getSecurityToken() {
    const config = new StsConfig({
        accessKeyId: process.env.ACCESS_KEY_ID,
        accessKeySecret: process.env.ACCESS_KEY_SECRET,
        endpoint: 'sts.cn-shanghai.aliyuncs.com'
    });
    
    const client = new Client(config);
    const runtime = new RuntimeOptions({});
    
    try {
        const response = await client.assumeRoleWithOptions({
            RoleArn: process.env.ROLE_ARN,
            RoleSessionName: 'iot-session',
            DurationSeconds: 3600
        }, runtime);
        
        return {
            accessKeyId: response.body.credentials.accessKeyId,
            accessKeySecret: response.body.credentials.accessKeySecret,
            securityToken: response.body.credentials.securityToken,
            expiration: response.body.credentials.expiration
        };
    } catch (error) {
        console.error('获取临时凭证失败:', error);
        throw error;
    }
}

exports.main = async (event, context) => {
    try {
        // 获取临时凭证
        const credentials = await getSecurityToken();
        
        // 配置 IoT 客户端
        const config = new Config({
            accessKeyId: credentials.accessKeyId,
            accessKeySecret: credentials.accessKeySecret,
            securityToken: credentials.securityToken,
            endpoint: 'iot.cn-shanghai.aliyuncs.com'
        });
        
        const client = new IoTClient(config);
        
        // 根据传入的操作类型执行不同的 IoT 操作
        const { action, params } = event;
        
        switch (action) {
            case 'pubBroadcast':
                return await handlePubBroadcast(client, params);
            case 'queryDevice':
                return await handleQueryDevice(client, params);
            default:
                return {
                    success: false,
                    message: '不支持的操作类型'
                };
        }
    } catch (error) {
        return {
            success: false,
            message: error.message,
            error: error
        };
    }
};

// 处理广播消息
async function handlePubBroadcast(client, params) {
    const request = new PubBroadcastRequest({
        iotInstanceId: params.iotInstanceId,
        topicFullName: params.topicFullName,
        messageContent: params.messageContent
    });
    
    const runtime = new RuntimeOptions({});
    const response = await client.pubBroadcastWithOptions(request, runtime);
    
    return {
        success: true,
        data: response
    };
}

// 处理设备查询
async function handleQueryDevice(client, params) {
    const request = new QueryDeviceRequest({
        iotInstanceId: params.iotInstanceId,
        productKey: params.productKey
    });
    
    const runtime = new RuntimeOptions({});
    const response = await client.queryDeviceWithOptions(request, runtime);
    
    return {
        success: true,
        data: response
    };
} 